using System.Collections.Generic;
using Comscore;
using UnityEngine;
using Voodoo.Sauce.Core;

namespace Voodoo.Sauce.Internal.Analytics
{
	public class ComscoreWrapper : MonoBehaviour
	{
		private const string TAG = "ComscoreWrapper";

		private const string CS_UCFR = "cs_ucfr";

		private ComscoreConfig _config;

		private ComscoreState _state = ComscoreState.Initializing;

		public static ComscoreWrapper Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
		}

		private void Start()
		{
		}

		private void Initialize(VoodooSauceInitCallbackResult result)
		{
			VoodooSettings voodooSettings = VoodooSettings.Load();
			if (_config == null)
			{
				_config = new ComscoreConfig
				{
					disabled = voodooSettings.ComscoreDisabled,
					allowedCountries = voodooSettings.ComscoreAllowedCountries
				};
			}
			if (_config.disabled)
			{
				VoodooLog.LogDebug(Module.ANALYTICS, "ComscoreWrapper", "Comscore is disabled");
				_state = ComscoreState.Disabled;
				return;
			}
			if (!_config.allowedCountries.Contains("*"))
			{
				List<string> list = new List<string>(_config.allowedCountries.ToLower().Split(','));
				if (string.IsNullOrEmpty(result.CountryCode) || !list.Contains(result.CountryCode.ToLower()))
				{
					VoodooLog.LogDebug(Module.ANALYTICS, "ComscoreWrapper", _config.allowedCountries + " doesn't contain user's country " + result.CountryCode);
					_state = ComscoreState.NotAllowedCountry;
					return;
				}
			}
			if (!result.AdsConsentGranted || result.IsEmbargoCountry)
			{
				VoodooLog.LogDebug(Module.ANALYTICS, "ComscoreWrapper", "Ads consent not granted");
				_state = ComscoreState.AdsConsentNotGranted;
				return;
			}
			string comscorePublisherId = voodooSettings.ComscorePublisherId;
			if (string.IsNullOrEmpty(comscorePublisherId))
			{
				VoodooLog.LogError(Module.ANALYTICS, "ComscoreWrapper", "Comscore publisher id is empty");
				_state = ComscoreState.PublisherKeyEmpty;
			}
			else
			{
				InitializeSdk(comscorePublisherId);
			}
		}

		private void InitializeSdk(string publisherId)
		{
			Dictionary<string, string> labels = new Dictionary<string, string> { { "cs_ucfr", "1" } };
			PublisherConfiguration config = new PublisherConfiguration.Builder().PublisherId(publisherId).PersistentLabels(labels).Build();
			Comscore.Analytics.Configuration.AddClient(config);
			if (VoodooLog.IsDebugLogsEnabled)
			{
				Comscore.Analytics.Configuration.EnableImplementationValidationMode();
			}
			Comscore.Analytics.Start();
			_state = ComscoreState.Initialized;
			VoodooLog.LogDebug(Module.ANALYTICS, "ComscoreWrapper", "Comscore is initialized");
		}

		public string GetStateDesc()
		{
			return _state.ToString();
		}
	}
}
